package com.zjlanyun.erp.interior.production;

import android.content.Intent;
import android.media.MediaDataSource;
import android.os.Build;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.aihook.alertview.library.AlertView;
import com.aihook.alertview.library.OnItemClickListener;
import com.alibaba.fastjson.JSON;
import com.yolanda.nohttp.rest.Response;
import com.zjlanyun.erp.Data;
import com.zjlanyun.erp.R;
import com.zjlanyun.erp.network.WebApi;
import com.zjlanyun.erp.nohttp.HttpRequest;
import com.zjlanyun.erp.nohttp.SimpleHttpListener;
import com.zjlanyun.erp.rfid.m10.u8.activity.OutPowerActivity;
import com.zjlanyun.erp.utils.Toastor;
import com.zjlanyun.erp.view.BaseRFIDActivity;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;

import butterknife.Bind;
import butterknife.OnClick;

public class Merge extends BaseRFIDActivity {

    @Bind(R.id.et_FQty) EditText et_FQty;

    @Bind(R.id.tv_result) TextView tv_result;
    @Bind(R.id.tv_status) TextView tv_status;
    @Bind(R.id.ll_submit) LinearLayout ll_submit;
    @Bind(R.id.list) LinearLayout list;

    private boolean scaning = false;
    private String apiUrl = "";
    private String epc = "";
    private ArrayList<String> mEpcList;
    private ArrayList<HashMap<String, Object>> mDataList;
    private LayoutInflater mInflater;
    private boolean querying = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.merge);
        initBaseView();
        initView();
    }

    private void initView() {
        apiUrl = WebApi.production();
        Bundle bundle = getIntent().getExtras();
        title.setText(bundle.getString("title"));

        mEpcList = new ArrayList<>();
        mDataList = new ArrayList<>();
        ll_submit.setVisibility(View.VISIBLE);
        mInflater = LayoutInflater.from(mContext);

        ll_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mEpcList.size() > 0) {
                    new AlertView("提示", "有未提交的数据，确定退出当前页吗？", "取消", new String[]{"确定"}, null, mContext, AlertView.Style.AlertDialog, new OnItemClickListener() {
                        @Override
                        public void onItemClick(Object o, int position) {
                            if (position == 0) {
                                finish();
                            }
                        }
                    }).show();
                } else {
                    finish();
                }
            }
        });
    }

    /**
     * 开始扫描
     */
    public void startScan() {
        tv_status.setText("盘询开始");
        scanNumber = 1;
        scaning = true;
        super.startScan();
    }

    /**
     * 停止扫描
     */
    public void stopScan() {
        tv_status.setText("盘询结束");
        scaning = false;
        super.stopScan();
    }

    public void refreshText() {
        super.refreshText();
        tv_result.setText(String.format("扫描到:%d个", m_curInventoryBuffer.lsTagList.size()));
        if (m_curInventoryBuffer.lsTagList.size() > 0) {
            String strEPC = m_curInventoryBuffer.lsTagList.get(0).getStrEPC().replace(" ", "");
            if (!mEpcList.contains(strEPC) && !querying) {
                querying = true;
                epc = strEPC;
                getProductInfo();
            } else if (mEpcList.contains(strEPC)) {
                //判断是否已经扫描了白卡
                boolean master = false;
                if (mDataList.size() > 0) {
                    //复卷拆分下判断母卷提示母卷已经扫描
                    for (HashMap<String, Object> item : mDataList) {
                        if (item.get("isMaster").toString().equals("1") && item.get("FBillNO").toString().equals(strEPC)) {
                            master = true;
                        }
                    }
                }
                if (master) {
                    Toastor.getInstance().showShortToast("该卡为母卷卡，已扫描");
                } else {
                    Toastor.getInstance().showShortToast("该卡为子卷卡，已扫描");
                }
            }
        }
    }

    /**
     * 获取产品信息
     */
    private void getProductInfo() {
        HashMap<String, Object> param = new HashMap<>();
        param.put("epc", epc);
        param.put("FGongXuNO", "104");
        param.put("FActionFlag", "bingjuan");
        HttpRequest client = new HttpRequest(mContext, apiUrl, "getProductInfo", JSON.toJSONString(param), true, true);
        client.send(new SimpleHttpListener<JSONObject>() {
            @Override
            public void onSucceed(int what, Response<JSONObject> response) {
                JSONObject data = response.get().optJSONObject("data");
                HashMap<String, Object> map = new HashMap<String, Object>();
                mEpcList.add(epc);
                View itemView = mInflater.inflate(R.layout.merge_item, null);
                TextView tvepc = (TextView) itemView.findViewById(R.id.tv_epc);
                tvepc.setText(data.optString("epc"));
                TextView tvFGongxuName = (TextView) itemView.findViewById(R.id.tv_FGongxuName);
                tvFGongxuName.setText(data.optString("FGongxuName"));
                TextView fname = (TextView) itemView.findViewById(R.id.tv_FName);
                fname.setText(data.optString("FName"));
                TextView pro_type = (TextView) itemView.findViewById(R.id.tv_pro_type);
                if (mEpcList.size() == 1) {
                    map.put("isMaster", "1");
                    pro_type.setText("（母卷）");
                } else {
                    map.put("isMaster", "0");
                    pro_type.setText("（子卷）");
                }
                TextView fbatchno = (TextView) itemView.findViewById(R.id.tv_FBatchNO);
                fbatchno.setText(data.optString("FBatchNO"));
                TextView fnumber = (TextView) itemView.findViewById(R.id.tv_FNumber);
                fnumber.setText(data.optString("FNumber"));
                map.put("FBillNO", data.optString("epc"));
                map.put("FInterID", data.optString("FInterID"));
                map.put("FDevNumber", data.optString("FDevNumber"));
                map.put("FMacSpeed", data.optString("FMacSpeed"));
                map.put("FBatchNO", data.optString("FBatchNO"));
                map.put("FQty", data.optDouble("FQty"));
                map.put("FCLQty", data.optDouble("FCLQty"));

                list.addView(itemView);
                mDataList.add(map);
                querying = false;
            }

            @Override
            public void onError(int what, Response<JSONObject> response) {
                querying = false;
            }
        });
    }

    /**
     * 提交
     */
    @OnClick(R.id.ll_submit)
    public void postMerge() {
        if (et_FQty.getText().toString().equals("")) {
            Toastor.getInstance().showShortToast("请输入总米数");
            return;
        } else if (mEpcList.size() < 2) {
            Toastor.getInstance().showShortToast("合并至少2卷");
            return;
        }
        HashMap<String, Object> param = new HashMap<>();
        param.put("list", JSON.toJSONString(mDataList));
        param.put("FQty", et_FQty.getText().toString());
        param.put("FGongXuNO", "104");
        param.put("FActionFlag", "bingjuan");
        HttpRequest client = new HttpRequest(mContext, apiUrl, "postMerge", JSON.toJSONString(param), true, true);
        client.send(new SimpleHttpListener<JSONObject>() {
            @Override
            public void onSucceed(int what, Response<JSONObject> response) {
                clean();
                Toastor.getInstance().showShortToast(R.string.submit_success);
            }
        });
    }

    private void clean() {
        et_FQty.setText("");
        list.removeAllViews();
        mDataList.clear();
        mEpcList.clear();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == 80 && Build.MODEL.equals(Data.RFID_DEVICE)) {
            if (scaning) {
                stopScan();
            } else {
                startScan();
            }
        } else if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            if (mEpcList.size() > 0) {
                new AlertView("提示", "有未提交的数据，确定退出当前页吗？", "取消", new String[]{"确定"}, null, mContext, AlertView.Style.AlertDialog, new OnItemClickListener() {
                    @Override
                    public void onItemClick(Object o, int position) {
                        if (position == 0) {
                            finish();
                        }
                    }
                }).show();
                return false;
            }
        } else if ((keyCode == 131 && Build.MODEL.equals(Data.RFID_DEVICE)) || (keyCode == 132 && Build.MODEL.equals(Data.RFID_DEVICE)) || (keyCode == 133 && Build.MODEL.equals(Data.RFID_DEVICE))) {
            Intent intent = new Intent(mContext, OutPowerActivity.class);
            intent.putExtra("from", "RFID" + className);
            startActivity(intent);
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }
}
